<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryData.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :data="depts"
          node-key="id"
          :props="{label: 'name'}"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="treeChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="$refs.iptExcel.showExcelDialog= true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="180px">
            <template slot-scope="{row}">
              <!-- {{ row }} -->
              <el-button size="mini" type="text" @click="$router.push('/employee/detail/' + row.id)">查看</el-button>
              <el-button size="mini" type="text" @click="openAssignRole(row.id)">角色</el-button>&nbsp;
              <el-popconfirm
                title="确认删除吗"
                @onConfirm="delRow(row.id)"
              >
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :current-page="queryData.page"
            :page-size="queryData.pagesize"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
      </div>
    </div>
    <import-excel ref="iptExcel" @uploadSuccess="initData" />
    <assignRole ref="assignRole" />
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { delEmpApi, exportEmpApi, getEmpInfoApi, getEmpListApi } from '@/api/imployee'
import importExcel from './components/import-excel.vue'
import FileSaver from 'file-saver'
import assignRole from '@/views/employee/components/assign-role'
export default {
  name: 'Employee',
  components: { importExcel, assignRole },
  data() {
    return {
      depts: [],
      queryData: {
        page: 1,
        pagesize: 10,
        keyword: '',
        departmentId: ''
      },
      list: [],
      total: 0
    }
  },
  async created() {
    await this.getDeptList()
    this.initData()
  },
  methods: {
    // 获取组织架构
    async getDeptList() {
      const res = await getDepartment()
      // console.log(res)
      this.depts = transListToTreeData(res, 0)
      if (this.depts.length === 0) return
      this.queryData.departmentId = this.depts[0].id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.depts[0].id)
      })
    },
    async initData() {
      const res = await getEmpListApi(this.queryData)
      // console.log(res)
      this.list = res.rows
      this.total = res.total
    },
    currentChange(val) {
      this.queryData.page = val
      this.initData()
    },
    treeChange(val) {
      this.queryData.departmentId = val.id
      this.queryData.page = 1
      this.initData()
    },
    changeValue() {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryData.page = 1
        this.initData()
      }, 300)
    },
    async exportEmployee() {
      const res = await exportEmpApi()
      console.log(res)
      /* const url = URL.createObjectURL(res)
      const a = document.createElement('a')
      a.href = url
      a.download = '员工信息.xlsx'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a) */
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    async delRow(id) {
      await delEmpApi(id)
      this.$message.success('删除成功')
      if (this.queryData.page > 1 && this.list.length === 1) this.queryData.page--
      this.initData()
    },
    // 打开关联角色弹框
    async openAssignRole(id) {
      // 根据ID查询该员工的信息，获取角色，赋给checkRole
      const res = await getEmpInfoApi(id)
      console.log(res)
      this.$refs.assignRole.userId = id
      this.$refs.assignRole.checkRole = res.roleIds
      this.$refs.assignRole.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
